<?php

namespace App\Http\Controllers\Admin\V1;

use App\Exports\QuestionExcelModel;
use App\Exports\QuestionExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\QuestionRequest;
use App\Imports\QuestionImport;
use App\Models\Question;
use App\Models\Role;
use App\Services\Questions\QuestionInterface;
use App\Transformers\Admin\QuestionsTransformer;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class QuestionController extends Controller
{
    /**
     * 显示题库的列表
     *
     * @return Response
     * @throws AuthorizationException
     */

    public function index()
    {
        // 验证授权
        $this->authorize('viewAny', Question::class);

        // 判断是否拥有查看所有数据的权限
        $root = $this->adminUser()->user()->hasRole(Role::SUPER_ADMIN);

        // 获取自己以及自己子级部门下所有用户id
        $ids = userIdAndAllChildrenId();

        // 不显示子题
        $questions = Question::where('pid', null)
            ->when(!$root, function ($query) use ($ids) {
                $query->whereIn('user_id', $ids);
            })
            ->pimp()->paginate($this->pageLimit());

        return $this->response->paginator($questions, new QuestionsTransformer());
    }

    /**
     * 添加题库
     *
     * @param QuestionRequest $request
     * @return \Dingo\Api\Http\Response
     * @throws AuthorizationException
     */
    public function store(QuestionRequest $request)
    {
        // 验证授权
        $this->authorize('create', Question::class);

        // 获取类名
        $namespace = '\\App\\Services\\Questions\\Type\\' . ucfirst($request->input('type'));

        // 判断类名是否存在
        if (!class_exists($namespace)) {
            return $this->response->errorNotFound($namespace . '未定义');
        }

        // 解析类
        $class = resolve($namespace);

        // 判断类是否实现QuestionInterface的接口
        if (!$class instanceof QuestionInterface) {
            return $this->response->errorNotFound('QuestionInterface未实现');
        }

        $class->store($request);

        return $this->response->created();
    }

    /**
     * 题库详情
     *
     * @param Question $question
     * @return Response
     * @throws AuthorizationException
     */
    public function show(Question $question)
    {
        // 验证授权
        $this->authorize('view', $question);

        // 试题
        $data = $question->subsystem()->pimp()->paginate($this->pageLimit());

        return $this->response->paginator($data, new QuestionsTransformer());
    }

    /**
     * 修改题库
     *
     * @param QuestionRequest $request
     * @param Question $question
     * @return \Dingo\Api\Http\Response
     * @throws AuthorizationException
     */
    public function update(QuestionRequest $request, Question $question)
    {
        // 验证授权
        $this->authorize('update', $question);

        // 删除可能传过来的type字段
        $request->offsetUnset('type');

        // 获取类名
        $namespace = '\\App\\Services\\Questions\\Type\\' . ucfirst($question->type);

        // 判断类名是否存在
        if (!class_exists($namespace)) {
            return $this->response->errorNotFound($namespace . '未定义');
        }

        // 解析类
        $class = resolve($namespace);

        // 判断类是否实现QuestionInterface的接口
        if (!$class instanceof QuestionInterface) {
            return $this->response->errorNotFound('QuestionInterface未实现');
        }

        $class->update($request, $question);

        return $this->response->noContent();
    }

    /**
     * 删除一题或者多题
     *
     * @param $ids
     * @return Response
     * @throws AuthorizationException
     */
    public function destroy($ids)
    {
        // 分割传过来的id
        $idArr = explode(',', $ids);

        foreach (Question::whereIn('id', $idArr)->get() as $model) {
            // 验证授权
            $this->authorize('delete', $model);

            // 执行删除
            $model->delete();
        }

        return $this->response->noContent();
    }

    /**
     * 修改题目状态 已审核，未审核
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     * @throws AuthorizationException
     */
    public function status(Request $request)
    {
        // 获取id
        $ids = explode(',', $request->input('ids'));

        // 获取修改的状态
        $status = $request->input('status');

        foreach (Question::whereIn('id', $ids)->get() as $model) {
            // 验证授权
            $this->authorize('update', $model);

            // 执行修改
            $model->update(['status' => $status]);
        }

        return $this->response->noContent();
    }

    /**
     * 导出功能
     *
     * @param Request $request
     * @return BinaryFileResponse
     */
    public function export(Request $request)
    {
        return Excel::download(new QuestionExport($request), 'question.xlsx', \Maatwebsite\Excel\Excel::XLSX);
    }

    /**
     * 导入功能
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => ['bail', 'required', 'file'],
        ]);

        //获取文件类型后缀
        $extension = $request->file('file')->getClientOriginalExtension();

        if ($extension != 'xlsx') {
            return $this->response->error('上传的文件不是excel文件', 422);
        }

        Excel::import(new QuestionImport(), $request->file('file'));

        return $this->response->noContent();
    }

    /**
     * 下载Excel模板
     */
    public function excel()
    {
        return Excel::download(new QuestionExcelModel(), 'question.model.xlsx', \Maatwebsite\Excel\Excel::XLSX);
    }
}
